
// Definition for a binary tree node.
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution
{
public:
    int helper(TreeNode *root, int sum)
    {
        if (!root)
            return 0;
        // 得到右子树的和
        int right_sum = helper(root->right, sum);
        // 改变val
        root->val += right_sum;
        root->val += sum;
        // 返回左子树合 加 右子树合 加当前值
        return helper(root->left, root->val) + root->val - sum;
    }
    TreeNode *convertBST(TreeNode *root)
    {
        helper(root, 0);
        return root;
    }
};